package com.drinks.yiniang.ui.widget.view;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

import com.drinks.yiniang.R;
import com.drinks.yiniang.common.camera.CameraInterface;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.ScreenSizeUtils;

/**
 * @author han
 * @date 2019/12/20
 */
public class CameraSurfacePreview extends SurfaceView implements CameraInterface.CameraOpenOverCallback, SurfaceHolder.Callback {

    private Context mContext;
    private SurfaceHolder mSurfaceHolder;
    private FoucsView mFoucsView;
    private View bottomView;

    private boolean firstTouch = true;

    private float screenProp = 0f;
    private float firstTouchLength = 0;

    //缩放梯度
    private int zoomGradient = 0;
    private int layout_width;

    public CameraSurfacePreview(Context context) {
        this(context, null);
    }

    public CameraSurfacePreview(Context paramContext, AttributeSet paramAttributeSet) {
        this(paramContext, paramAttributeSet, 0);

    }

    public CameraSurfacePreview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        mSurfaceHolder = getHolder();
        mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceHolder.addCallback(this);

        layout_width = ScreenSizeUtils.getWidth(getContext());
        //缩放梯度
        zoomGradient = (int) (layout_width / 16f);

        setSurfaceOntouchListener();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        float widthSize = getMeasuredWidth();
        float heightSize = getMeasuredHeight();
        if (screenProp == 0) {
            screenProp = heightSize / widthSize;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        new Thread() {
            @Override
            public void run() {
                CameraInterface.getInstance().doOpenCamera(CameraSurfacePreview.this);
            }
        }.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        CameraInterface.getInstance().doDestroyCamera();
    }

    @Override
    public void cameraHasOpened() {
        CameraInterface.getInstance().doStartPreview(this.getHolder(), screenProp);
        setSuitableParams();
    }

    //生命周期onResume
    public void onResume() {
        LogUtils.i("JCameraView onResume");
        CameraInterface.getInstance().doStartPreview(getSurfaceHolder(), screenProp);
    }

    //生命周期onPause
    public void onPause() {
        LogUtils.i("JCameraView onPause");
        CameraInterface.getInstance().isPreview(false);
        CameraInterface.getInstance().doStopPreview();
    }

    public void swtich(float screenProp) {
        CameraInterface.getInstance().switchCamera(getSurfaceHolder(), screenProp);
    }

    public void setFoucsView(FoucsView mFoucsView, View bottomView) {
        this.mFoucsView = mFoucsView;
        this.bottomView = bottomView;
    }

    private void setSurfaceOntouchListener() {
        setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        if (event.getPointerCount() == 1) {
                            //显示对焦指示器
                            if(handlerFoucs(event.getX(), event.getY())) {
                                CameraInterface.getInstance().handleFocus(getContext(), event.getX(), event.getY(), new CameraInterface.FocusCallback() {
                                    @Override
                                    public void focusSuccess() {
                                        if(mFoucsView != null) {
                                            mFoucsView.setVisibility(INVISIBLE);
                                        }
                                    }
                                });
                            }
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (event.getPointerCount() == 1) {
                            firstTouch = true;
                        }
                        if (event.getPointerCount() == 2) {
                            //第一个点
                            float point_1_X = event.getX(0);
                            float point_1_Y = event.getY(0);
                            //第二个点
                            float point_2_X = event.getX(1);
                            float point_2_Y = event.getY(1);

                            float result = (float) Math.sqrt(Math.pow(point_1_X - point_2_X, 2) + Math.pow(point_1_Y - point_2_Y, 2));

                            if (firstTouch) {
                                firstTouchLength = result;
                                firstTouch = false;
                            } else {
                                if ((int) (result - firstTouchLength) / zoomGradient != 0) {
                                    int zoom = (int) ((result - firstTouchLength) / 12);
                                    CameraInterface.getInstance().setZoom(zoom);
                                    firstTouch = true;
                                    Log.i("CJT", "result = " + (result - firstTouchLength));
                                }
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        firstTouch = true;
                        break;
                }
                return true;
            }
        });
    }

    private void setSuitableParams() {
        if (screenProp > 1.8) { //屏幕的宽高比大于1.8的时候处理
            float previewProp = CameraInterface.getInstance().getPreviewProp();
            if (previewProp == 0) {   //获取的size宽高比
                return;
            }
            int measuredHeight = getMeasuredHeight();
            int measuredWidth = getMeasuredWidth();
            float clacWidth = measuredHeight / previewProp;   //计算出要显示的预览界面的宽度。
            ViewGroup.LayoutParams layoutParams = getLayoutParams();
            if (layoutParams == null) {
                layoutParams = new ViewGroup.LayoutParams((int) clacWidth, measuredHeight);
            }
            if (clacWidth > 800 && Math.abs(clacWidth - measuredWidth) > clacWidth * 0.1F) {  //计算的宽度大于 800 并且和显示正常的布局的误差超过10%
                layoutParams.width = (int) clacWidth;
            }
            final ViewGroup.LayoutParams finalLayoutParams = layoutParams;
            post(new Runnable() {
                @Override
                public void run() {
                    setLayoutParams(finalLayoutParams);
                }
            });
        }
    }

    public SurfaceHolder getSurfaceHolder() {
        return this.mSurfaceHolder;
    }

    public boolean handlerFoucs(float x, float y) {
        mFoucsView.setVisibility(VISIBLE);
        if (x < mFoucsView.getWidth() / 2) {
            x = mFoucsView.getWidth() / 2;
        }
        if (x > layout_width - mFoucsView.getWidth() / 2) {
            x = layout_width - mFoucsView.getWidth() / 2;
        }
        if (y < mFoucsView.getWidth() / 2) {
            y = mFoucsView.getWidth() / 2;
        }
        if (y > getHeight() - mFoucsView.getWidth() / 2) {
            y = getHeight() - mFoucsView.getWidth() / 2;
        }
        mFoucsView.setX(x - mFoucsView.getWidth() / 2);
        mFoucsView.setY(y - mFoucsView.getHeight() / 2);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(mFoucsView, "scaleX", 1, 0.6f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(mFoucsView, "scaleY", 1, 0.6f);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(mFoucsView, "alpha", 1f, 0.4f, 1f, 0.4f, 1f, 0.4f, 1f);
        AnimatorSet animSet = new AnimatorSet();
        animSet.play(scaleX).with(scaleY).before(alpha);
        animSet.setDuration(400);
        animSet.start();
        return true;
    }

}
